#include "urldelegate.h"

#include <QApplication>
#include <QPainter>

#include "urltask.h"

UrlDelegate::UrlDelegate(QObject *parent)
    : QItemDelegate(parent)
{
    m_pixmaps[UrlTask::INPROGRESS] = QPixmap(":/icons/inprogress");
    m_pixmaps[UrlTask::ERROR] = QPixmap(":/icons/error");
    m_pixmaps[UrlTask::STOPPED] = QPixmap(":/icons/stopped");
    m_pixmaps[UrlTask::FINISHED] = QPixmap(":/icons/finished");
}

void UrlDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    UrlTask *task = static_cast<UrlTask *>(index.internalPointer());
    switch (index.column())
    {
    case UrlTask::PROGRESS:
    {
        QStyleOptionProgressBar bar;
        bar.state = QStyle::State_Enabled;
        bar.direction = QApplication::layoutDirection();
        bar.rect = option.rect;
        bar.fontMetrics = QApplication::fontMetrics();
        bar.textAlignment = Qt::AlignCenter;
        bar.textVisible = true;
        bar.rect = option.rect;
        bar.minimum = 0;
        bar.maximum = 100;
        bar.progress = task->get_progress();
        bar.text = QString::number(task->get_progress()) + " %";
        QApplication::style()->drawControl(QStyle::CE_ProgressBar, &bar, painter);
        break;
    }
    case UrlTask::STATUS:
    {
        int width = option.rect.height() > option.rect.width() ?
                                    option.rect.width() : option.rect.height();
        QSize size(width, width);
        painter->drawPixmap(option.rect.topLeft(), m_pixmaps[task->get_status()].scaled(size));
        break;
    }
    case UrlTask::URL:
    {
        painter->drawText(option.rect, task->get_url());
        break;
    }
    case UrlTask::FILE:
    {
        painter->drawText(option.rect, task->get_file());
        break;
    }
    }
}
